package com.zenith.gateway.service.impl;

import com.zenith.common.result.Result;
import com.zenith.gateway.feign.PermissionFeignClient;
import com.zenith.gateway.po.dto.PermissionDTO;
import com.zenith.gateway.service.PermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionFeignClient permissionFeignClient;

    @Override
    public boolean hasPermission(String path, String method, String role) {
        try {
            Result<List<PermissionDTO>> result = permissionFeignClient.selectPermissionsByRole(role);
            if (result != null && result.getCode() == 200 && result.getData() != null) {
                List<PermissionDTO> permissions = result.getData();
                return permissions.stream()
                        .anyMatch(p -> path.matches(p.getUrl())
                                && method.equalsIgnoreCase(p.getMethod()));
            }
        } catch (Exception e) {
            log.error("获取角色权限失败，角色: {}", role, e);
        }
        return false;
    }
}